import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const { logout, fetchUserInfo, requireLogin } = require('../../utils/api.js');
const { updatePhone, validatePhone, getEmployees } = require('../../utils/user-api.js');

Page({
  behaviors: [themeChangeBehavior],
  
  data: {
    userInfo: null,
    showPhoneDialog: false,
    newPhone: '',
    isUpdatingPhone: false,
    employees: [],
    loadingEmployees: false,
    showEmployees: false
  },

  onLoad() {
    if (requireLogin()) {
      this.loadUserInfo();
    }
  },

  async onShow() {
    await this.loadUserInfo();
    // 检查用户角色，如果是组长(role == 2)，则加载组员列表
    if(this.data.userInfo && this.data.userInfo.role == 2){
      this.loadEmployees();
    }
  },

  async loadUserInfo() {
    try {
      // 先从本地获取基础用户信息
      const localUserInfo = wx.getStorageSync('userInfo');
      if (localUserInfo) {
        this.setData({ userInfo: localUserInfo });
      }
      
      // 然后从服务器获取最新的用户信息
      const result = await fetchUserInfo();
      
      if (result.message == "操作成功") {
        this.setData({ userInfo: result.data });
      } else {

        // 如果获取失败但本地有信息，继续使用本地信息
        if (!localUserInfo) {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          });
        }
      }
    } catch (error) {

      // 如果出现异常且本地没有用户信息，跳转到登录页
      const localUserInfo = wx.getStorageSync('userInfo');
      if (!localUserInfo) {
        wx.redirectTo({
          url: '/pages/login/login'
        });
      }
    }
  },

  // 修改密码
  onChangePassword() {
    wx.navigateTo({
      url: '/pages/change-password/change-password?firstLogin=false'
    });
  },

  // 修改手机号
  onChangePhone() {
    this.setData({
      showPhoneDialog: true,
      newPhone: this.data.userInfo?.phone || ''
    });
  },

  // 手机号输入
  onPhoneInput(e) {
    this.setData({
      newPhone: e.detail.value
    });
  },

  // 确认修改手机号
  async onPhoneConfirm() {
    const { newPhone } = this.data;
    
    // 验证手机号格式
    const validation = validatePhone(newPhone);
    if (!validation.isValid) {
      wx.showToast({
        title: validation.message,
        icon: 'none'
      });
      return;
    }

    // 检查是否与当前手机号相同
    if (newPhone === this.data.userInfo?.phone) {
      wx.showToast({
        title: '新手机号与当前手机号相同',
        icon: 'none'
      });
      return;
    }

    if (this.data.isUpdatingPhone) {
      return;
    }

    this.setData({ isUpdatingPhone: true });

    try {
      wx.showLoading({
        title: '修改中...',
        mask: true
      });

      const result = await updatePhone(newPhone);
      

      wx.hideLoading();

      if (result.message == "操作成功") {
        wx.showToast({
          title: '修改成功',
          icon: 'success'
        });

        // 关闭对话框
        this.setData({
          showPhoneDialog: false,
          newPhone: ''
        });

        // 重新加载用户信息
        this.loadUserInfo();

      } else {
        wx.showToast({
          title: result.message || '修改失败',
          icon: 'none'
        });
      }

    } catch (error) {

      wx.hideLoading();
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ isUpdatingPhone: false });
    }
  },

  // 取消修改手机号
  onPhoneCancel() {
    this.setData({
      showPhoneDialog: false,
      newPhone: ''
    });
  },

  // 加载组员列表
  async loadEmployees() {
    if (this.data.loadingEmployees) return;
    
    this.setData({ loadingEmployees: true });
    
    try {
      const result = await getEmployees();
      
      if (result.message == "操作成功") {
        this.setData({ 
          employees: result.data || [],
          showEmployees: true
        });
      } else {

        this.setData({ 
          employees: [],
          showEmployees: false
        });
        
        // 如果是权限问题或者用户不是组长，不显示错误提示
        if (result.message && !result.message.includes('权限')) {
          wx.showToast({
            title: '获取组员列表失败',
            icon: 'none'
          });
        }
      }
    } catch (error) {

      this.setData({ 
        employees: [],
        showEmployees: false
      });
    } finally {
      this.setData({ loadingEmployees: false });
    }
  },

  // 切换组员列表显示状态
  toggleEmployees() {
    this.setData({
      showEmployees: !this.data.showEmployees
    });
  },

  onLogout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
}); 